const { verifyToken } = require('../utils/token');

// 带有数据内容的数据处理
module.exports.SQLData = (err, result, msg) => {
  if (err) {
    return {
      code: 500,
      success: false,
      msg,
      data: err,
    };
  } else {
    return {
      code: 200,
      success: true,
      data: { ...result },
    };
  }
};

module.exports.SuccessData = function (result) {
  return {
    code: 200,
    success: true,
    data: { ...result },
  };
};

// 简单的数据处理
module.exports.SimpleData = (code, msg) => {
  return {
    code,
    msg,
  };
};

// 判断对象是否为空对象
module.exports.returnObjIsNull = (obj) => {
  if (Object.keys(obj).length > 0) {
    return true;
  } else {
    return false;
  }
};

// 从token中获取用户名字
module.exports.returnValueFromToken = async (token, key) => {
  try {
    const { data: user } = await verifyToken(token);
    return user[key];
  } catch (err) {
    console.log(err);
  }
};

//时间格式化
module.exports.returnDate = (inputTime) => {
  let date = new Date(inputTime); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
  let y = date.getFullYear();
  let m = date.getMonth() + 1;
  m = m < 10 ? '0' + m : m;
  let d = date.getDate();
  d = d < 10 ? '0' + d : d;
  let h = date.getHours();
  h = h < 10 ? '0' + h : h;
  let minute = date.getMinutes();
  let second = date.getSeconds();
  minute = minute < 10 ? '0' + minute : minute;
  second = second < 10 ? '0' + second : second;
  return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
};
